class Group < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  # attr_accessible :title, :body
  has_many :user_groupships,:dependent => :destroy
  has_many :users, :through => :user_groupships, :class_name => "Admin", :foreign_key => "user_id"
  has_many :sub_groups,:dependent => :destroy
  has_many :groups_permissions,:dependent => :destroy
  has_many :permissions, :through => :groups_permissions

  has_many :subs, through: :sub_groups, source: :sub, class_name: "Group"

  attr_accessor :entities, :actions, :level

  validates_presence_of :name, :category
  validates_uniqueness_of :name

  CATEGORIES = %w{Department Entity Role Simple}

  def all_users
    users = UserGroupship.where(group_id: self.id).uniq.pluck(:user_id)
    sub_gous = SubGroup.where(group_id: self.id).uniq.pluck(:subgroup_id)
    groups = Group.where(id: sub_gous).all
    gusers = []
    gusers = groups.collect(&:all_users).flatten if not groups == []
    (users + gusers).uniq
  end

  def child_groups
    groups = SubGroup.where(group_id: self.id).uniq.pluck(:subgroup_id)
    Group.where(id: groups).all
  end

end
